#include "comm.h"
#include <unistd.h>

int main()
{
  key_t key = ftok(PATH_NAME, PRO_ID);
  if(key < 0) {
    perror("ftok");
    return 1;
  }
  int shmid = shmget(key, SIZE, IPC_CREAT|IPC_EXCL|0666); // 创建共享,返回共享内存的id
  if(shmid < 0) {
    perror("shmid");
    return 2;
  }
  printf("key: 0x%x, shmid: %d\n", key, shmid);
  char* mem = (char*)shmat(shmid, NULL, 0); // 根据id挂载共享内存，由操作系统帮我们实现
  printf("server attaches successfully!\n");
  //sleep(15);
  
  // 进程可在此共享内存通信
  while(1) {
    sleep(1);
    printf("%s\n", mem);
  }



  int ret = shmdt(mem); // 卸载
  if(!ret) {
    printf("server detaches successfully!\n");
  }else {
    printf("server detaches faild!\n");
  }

  sleep(10);
  shmctl(shmid, IPC_RMID, NULL); // 清除共享内存
  printf("key: 0x%x, shmid: %d -> shm delete success\n", key, shmid);
  sleep(10);
  return 0;
}
